<template>
    <view class="pub_page pub_add_device">
        <pub-head headerName="demo" :headerConfig="headerConfig"></pub-head>
        <div class="page_box page_box_scroll" :style="{ 'height': `calc(100vh - ${headerHeight})` }">
            <div class="step_div">
                <div class="li" :class="step > 0 ? ' li_active' : ''">
                    <div class="num">1</div>
                    <div class="p">基础信息</div>
                </div>
                <div class="line"></div>
                <div class="li" :class="step > 1 ? ' li_active' : ''">
                    <div class="num">2</div>
                    <div class="p">功能配置</div>
                </div>
            </div>
            <div v-if="step == 1">
                <div class="lis_box">
                    <div class="title" @click="chooseJump({ openType: 4 })"><text class="xing">*</text> 选择区域
                        <image class="right_icon" mode="aspectFit"
                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_24.png" />
                    </div>
                    <div class="lis_div" v-if="chooseData.area != ''">
                        <div class="lis">
                            <div class="remark">
                                <image class="icon" mode="aspectFill"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_29.png" />{{
                                        chooseData.area.areaName }}
                            </div>
                            <div class="li">
                                <div class="p_1">创建时间</div>
                                <div class="p_2">{{ chooseData.area.createTime }}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lis_box">
                    <div class="title" @click="chooseJump({ openType: 1 })"><text class="xing">*</text> 收费方案
                        <image class="right_icon" mode="aspectFit"
                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_24.png" />
                    </div>
                    <div class="lis_div" v-if="chooseData.price_plan != ''">
                        <div class="lis">
                            <div class="remark">
                                <image class="icon" mode="aspectFill"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_26.png" />{{
                                        chooseData.price_plan.planName }}
                            </div>
                            <div class="li">
                                <div class="p_1">创建时间</div>
                                <div class="p_2">{{ chooseData.price_plan.createTime }}</div>
                            </div>
                            <div class="li">
                                <div class="p_1">收费类型</div>
                                <div class="p_2">{{ chooseData.price_plan.billingTypeName }}</div>
                            </div>
                            <div class="li">
                                <div class="p_1">价格(元/度)</div>
                                <div class="p_2">{{ chooseData.price_plan.priceConfig.unitPrice }}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lis_box">
                    <div class="title" @click="chooseJump({ openType: 2 })">预警方案(可选)
                        <image class="right_icon" mode="aspectFit"
                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_24.png" />
                    </div>
                    <div class="lis_div" v-if="chooseData.warn_scheme != ''">
                        <div class="lis">
                            <div class="remark">
                                <image class="icon" mode="aspectFill"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_27.png" />{{
                                        chooseData.warn_scheme.name }}
                            </div>
                            <div class="li">
                                <div class="p_1">创建时间</div>
                                <div class="p_2">{{ chooseData.warn_scheme.createTime }}</div>
                            </div>
                            <div class="li">
                                <div class="p_1">预警余额线</div>
                                <div class="p_2">{{ chooseData.warn_scheme.warnBalance }}</div>
                            </div>
                            <div class="li">
                                <div class="p_1">预警操作</div>
                                <div class="p_2">{{ chooseData.warn_scheme.warnMethodName }}</div>
                            </div>
                            <div class="li">
                                <div class="p_1">备注</div>
                                <div class="p_2">{{ chooseData.warn_scheme.remark }}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div style="height:48rpx"></div>
                <div>
                    <div class="pub_btn pub_btn_big_normal" @click="stepClick()">下一步</div>
                    <div style="height:48rpx"></div>
                </div>
            </div>
            <div v-if="step == 2">
                <div class="pub_input">
                    <div class="li">
                        <div class="title"><text class="xing">*</text> 电表表号</div>
                        <div class="input input_right input_right_big">
                            <input class="inp" type="text" v-model="form.device_name" :disabled="deviceId ? true : false"
                                placeholder="请输入设备编码" placeholder-style="color:#bbb">
                            <image v-if="deviceId == ''" @click="openScan" class="right_icon right_icon_big"
                                mode="aspectFit"
                                src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_55.png" />
                        </div>
                    </div>
                </div>
                <div class="pub_input">
                    <div class="li" @click="chooseJump({ openType: 5 })">
                        <div class="title"><text class="xing">*</text> 选择房间</div>
                        <div class="input input_right">
                            <input class="inp" type="text" :value="chooseData.room ? chooseData.room.roomName : ''"
                                placeholder-style="color:#bbb" disabled>
                            <image class="right_icon" mode="aspectFit"
                                src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_24.png" />
                        </div>
                    </div>
                </div>
                <div class="lis_box">
                    <div class="title" @click="chooseJump({ openType: 6 })">选择住户（可选，可后续补录）
                        <image class="right_icon" mode="aspectFit"
                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_24.png" />
                    </div>
                    <div class="lis_div">
                        <div class="lis" v-for="(li, key) in chooseData.user" :key="key">
                            <div class="remark">
                                <image class="icon" mode="aspectFill"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_28.png" />{{
                                        li.username }}
                                <div class="right" v-if="li.status == 1"><text class="yuan"></text> 正常入住</div>
                                <div class="right right_1" v-else><text class="yuan"></text> 已禁用</div>
                            </div>
                            <div class="li">
                                <div class="p_1">手机号</div>
                                <div class="p_2">{{ li.phone }}</div>
                            </div>
                            <div class="li">
                                <div class="p_1">房间数</div>
                                <div class="p_2">{{ li.roomCount }}间</div>
                            </div>
                            <div class="edit" @click="deleteUser(key)">
                                <image class="icon" mode="aspectFit"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_53.png" />
                            </div>
                        </div>
                    </div>
                </div>
                <div style="height:50rpx"></div>
                <div class="btns_div">
                    <div class="btn_1" @click="step = 1">上一步</div>
                    <div class="btn_right" v-if="deviceId">
                        <div class="btn_4" @click="toSubmit(2)">保存</div>
                    </div>
                    <div class="btn_right" v-else>
                        <div class="btn_2" @click="toSubmit(1)">继续添加</div>
                        <div class="btn_3" @click="toSubmit(2)">保存</div>
                    </div>
                </div>
                <div style="height:48rpx"></div>
            </div>
        </div>
    </view>
</template>

<script>
export default {
    data() {
        return {
            headerConfig: {
                title: '',//标题栏内容
                header_color: '#fff'
            },
            headerHeight: getApp().globalData.headerHeight,

            step: 1,
            deviceId: '',
            form: {
                device_name: '',//设备名称/电表表号
                room_id: '',//房间id
                area_id: '',//区域id
                price_plan_id: '',//收费方案
                warn_scheme_id: '',//预警方案
                user_ids: [],//用户id
            },
            // 选择后显示的数据
            chooseData: {
                room: '',
                area: '',
                price_plan: '',
                warn_scheme: '',
                user: [],
            }
        };
    },
    onLoad(options) {
        this.deviceId = options.deviceId || '';
        if (this.deviceId) {
            this.step = options.step || 1;
            this.getDetail();
        }
        this.headerConfig.title = (this.deviceId ? '编辑' : '新增') + '设备';
        // 支付宝小程序设置状态栏文字颜色
        this.$comFun.setZfbNavigationBar();

        const that = this;
        uni.$off('addDeviceChooseBack');
        uni.$on('addDeviceChooseBack', function (data) {
            // console.log(data);
            if (data.openType == 1) {
                that.chooseData.price_plan = data.info;
                that.form.price_plan_id = Number(data.info.pricePlanId);
            }
            if (data.openType == 2) {
                that.chooseData.warn_scheme = data.info;
                that.form.warn_scheme_id = Number(data.info.Id);
            }
            if (data.openType == 4) {
                that.chooseData.area = data.info;
                that.form.area_id = Number(data.info.areaId);
                // 切换区域后，清除房间和住户
                that.chooseData.room = '';
                that.form.room_id = '';
                that.chooseData.user = [];
                that.form.user_ids = [];
            }
            if (data.openType == 5) {
                that.chooseData.room = data.info;
                that.form.room_id = Number(data.info.roomId);
                // 切换房间后，清除住户
                that.chooseData.user = [];
                that.form.user_ids = [];
            }
            if (data.openType == 6) {
                let find = that.chooseData.user.find(li => {
                    return li.userId == data.info.userId;
                })
                if (!find) {
                    that.chooseData.user.push(data.info);
                    that.form.user_ids.push(Number(data.info.userId));
                }
            }
        })
    },
    methods: {
        stepClick() {
            if (!this.form.area_id) {
                this.$comFun.toast('请选择区域');
                return;
            }
            if (!this.form.price_plan_id) {
                this.$comFun.toast('请选择收费方案');
                return;
            }
            this.step = 2;
        },
        toSubmit(sType) {
            const that = this;
            const form = JSON.parse(JSON.stringify(that.form));
            if (!form.device_name) {
                this.$comFun.toast('请填写电表表号');
                return;
            }
            if (!form.room_id) {
                this.$comFun.toast('请选择房间');
                return;
            }
            uni.showModal({
                title: '提示',
                content: '是否确定保存？',
                success: async function (modalRes) {
                    if (modalRes.confirm) {
                        that.$comFun.openLoading();
                        console.log(form);
                        let res;
                        if (form.warn_scheme_id == '') {
                            // delete form.warn_scheme_id;
                            form.warn_scheme_id = null
                        }
                        if (that.deviceId) {
                            res = await that.$request.put(`mobile/manager/device/bind/${that.deviceId}`, {
                                ...form,
                            });
                        } else {
                            res = await that.$request.post('mobile/manager/device/bind', form);
                        }
                        // console.log(res);
                        that.$comFun.closeLoading();
                        if (res.code == 200) {
                            that.$comFun.toast('保存成功');
                            uni.$emit(`addDeviceBack`);
                            if (sType == 1) {
                                that.form.device_name = '';
                                that.form.room_id = '';
                                that.form.user_ids = [];
                                that.chooseData.room = '';
                                that.chooseData.user = [];
                                // that.form = that.$options.data().form;
                                // that.chooseData = that.$options.data().chooseData;
                                // that.step = 1;
                            } else {
                                uni.$emit(`deviceUpdateBack_info`);
                                setTimeout(() => {
                                    that.$comFun.closeWin();
                                }, 1000)
                            }
                        } else {
                            that.$comFun.toast(res.msg);
                        }
                    }
                }
            });
        },
        deleteUser(key) {
            this.chooseData.user.splice(key, 1);
            this.form.user_ids.splice(key, 1);
        },
        openScan() {
            if (this.deviceId) {
                return;
            }
            const that = this;
            uni.scanCode({
                scanType: ['barCode','qrCode'],
                success: function (res) {
                    // console.log(res.result);
                    that.dealScan(res.result)
                },
                fail: function (err) {
                    that.$comFun.toast('失败，请稍后再试');
                },
            });
        },
        async dealScan(code) {
            this.$comFun.openLoading();
            const res = await this.$request.get(`/mobile/manager/device/${code}`);
            this.$comFun.closeLoading();
            // console.log(res);
            if (res.code == 200) {
                this.form.device_name = code;
            } else {
                this.$comFun.toast(res.msg);
            }
        },
        chooseJump(data) {
            let oData = {};
            if (data.openType == 5) {
                oData = {
                    areaId: this.chooseData.area.areaId,
                    areaName: this.chooseData.area.areaName,
                }
            }
            if (data.openType == 6) {
                if (!this.form.room_id) {
                    this.$comFun.toast('请先选择房间');
                    return;
                }
                oData = {
                    roomId: this.form.room_id
                }
            }
            this.$comFun.openWin('/pages/manage/manage_list', {
                ...data,
                ...oData,
                isChoose: true
            });
        },
        async getDetail() {
            const that = this;
            that.$comFun.openLoading();
            const res = await that.$request.get(`mobile/manager/device/detail/${that.deviceId}`, {});
            // console.log(res);
            that.$comFun.closeLoading();
            if (res.code == 200) {
                this.form = {
                    device_name: res.data?.name,//设备名称/电表表号
                    room_id: res.data?.sppcpRoom?.roomId || '',//房间id
                    area_id: res.data?.sppcpArea?.areaId || '',//区域id
                    price_plan_id: res.data?.sppcpPricePlan?.pricePlanId || '',//收费方案
                    warn_scheme_id: res.data?.sppcpWarnScheme?.Id && res.data?.sppcpWarnScheme?.Id != 0 ? res.data?.sppcpWarnScheme?.Id : '',//预警方案
                    user_ids: (res.data?.user || []).map(li => {
                        return li.userId;
                    }),//用户id
                };

                let price_plan = res.data?.sppcpPricePlan || '';
                let billingTypeArr = [{ id: 1, name: '固定电价' }, { id: 2, name: '梯度电价' }, { id: 3, name: '复费率电价' }];
                if (price_plan) {
                    // 梯度电价
                    if (price_plan.billingType == 2) {
                        let unitPriceArr = price_plan.priceConfig.tiers.map(li => {
                            return li.unitPrice
                        })
                        price_plan.priceConfig.unitPrice = unitPriceArr.join("、")
                    }
                    // 收费类型
                    let find = billingTypeArr.find(bli => {
                        return bli.id == price_plan.billingType
                    })
                    price_plan.billingTypeName = find ? find.name : '';
                }

                let warn_scheme = res.data?.sppcpWarnScheme?.Id && res.data?.sppcpWarnScheme?.Id != 0 ? res.data?.sppcpWarnScheme : '';
                if (warn_scheme) {
                    warn_scheme.warnMethodName = warn_scheme.sppcpWarnMethod?.name || '';
                }

                // 选择后显示的数据
                this.chooseData = {
                    room: res.data?.sppcpRoom || '',
                    area: res.data?.sppcpArea || '',
                    price_plan: price_plan,
                    warn_scheme: warn_scheme,
                    user: res.data?.user || [],
                };
                this.$forceUpdate();
                console.log(this.form, this.chooseData);
            }
        },
    },
};
</script>

<style lang="scss" scoped>
@import "@/common/css/index.scss";
</style>
